#!/usr/bin/env python3
#coding: utf-8

import subprocess
import time
from execute_command import ExecuteCommand
from execute_log import server_logger

def get_and_check_target(device_num: None | str, targets: list[str]) -> str:
    result = ''
    for target in targets:
        if not target.isalnum() or not target.isupper():
            continue
        if not device_num or device_num == target:
            result = target
            break
    if not result:
        raise Exception('HDC cannot find available devices')
    return result

class HDCClient:
    device_num: None | str = None
    executor: ExecuteCommand

    def __init__(self,
                 device_num: None | str = None,
                 executor: ExecuteCommand = ExecuteCommand()) -> None:
        self.executor = executor
        self.device_num = get_and_check_target(device_num, self.list_targets().split())

    def list_targets(self) -> str:
        execute_succeeded, out = self.executor.execute([f'hdc list targets'])
        return out

    def __create_cmd_list(self, command: str) -> list:
        return [f'hdc -t {self.device_num} shell {command}']

    def execute(self, command: str, timeout: int = 300) -> [bool, str]:
        execute_succeeded, out = self.executor.execute(self.__create_cmd_list(command), timeout)
        if not execute_succeeded:
            server_logger.error(f'execute error: {out}')
        return [execute_succeeded, out]
       

    def recv_file(self, mobile_file, local_path) -> None:
        self.executor.execute([f'hdc -t {self.device_num} file recv {mobile_file} {local_path}'])

    def send_file(self, local_file, mobile_path) -> bool:
        execute_succeeded, out = self.executor.execute([f'hdc -t {self.device_num} file send {local_file} {mobile_path}'])
        if not execute_succeeded:
            server_logger.error(f'send_file error: {e}')
            return False
        return True

    def mount(self) -> bool:
        execute_succeeded, out = self.execute('remount -o remount,rw /')
        return execute_succeeded
